package ru.nsu.fit.client.core.soap.get_user_stat;

import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import ru.nsu.fit.client.core.response.UserStatisticsData;
import ru.nsu.fit.client.core.soap.SOAPExecutor;

import java.util.AbstractMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class GetUserStat {
    private static final String WSDL_NAME = "get_user_stat";
    private static final String METHOD_NAME = "getUserStat";
    private static final String NAMESPACE = "http://get_user_stat.ws.fit.nsu.ru/";

    public static GetUserStatOutput execute(final String serverLocation, long userSessionId) throws Exception
    {
        String wsdlLocation = serverLocation + WSDL_NAME + "?wsdl";

        Set<Map.Entry<String, String>> params = new HashSet<Map.Entry<String,String>>();
        params.add(new AbstractMap.SimpleEntry<String, String>("userSessionId", String.valueOf(userSessionId)));

        SoapObject response = SOAPExecutor.executeSOAP(wsdlLocation, NAMESPACE, METHOD_NAME, params);

        GetUserStatOutput out = new GetUserStatOutput();
        out.setSuccessful(Boolean.parseBoolean(response.getPropertyAsString("successful")));
        if (response.hasProperty("errorMessage"))
        {
            out.setErrorMessage(response.getPropertyAsString("errorMessage"));
        }
        if (out.isSuccessful())
        {
            UserStatisticsData data = new UserStatisticsData();
            if (response.hasProperty("userRating"))
            {
                data.setUserRating(Integer.parseInt(response.getPropertyAsString("userRating")));
            }
            if (response.hasProperty("userRatingPosition"))
            {
                data.setUserRatingPosition(Integer.parseInt(response.getPropertyAsString("userRatingPosition")));
            }

            PropertyInfo info = new PropertyInfo();
            for (int i = 0; i < response.getPropertyCount(); ++i)
            {
                response.getPropertyInfo(i, info);
                if (info.getName().equals("askedQuestionIds"))
                {
                    data.getMyQuestions().add(Integer.parseInt(info.getValue().toString()));
                }
                else if (info.getName().equals("answeredQuestionIds"))
                {
                    data.getAnsweredQuestions().add(Integer.parseInt(info.getValue().toString()));
                }
            }

            data.setAnsweredQuestionsCount(data.getAnsweredQuestions().size());
            data.setAskedQuestionsCount(data.getMyQuestions().size());

            out.setStatistics(data);
        }

        return out;
    }
}
